package service

import (
	"duoke/utils/api345"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/storage"
	"errors"
	"github.com/gin-gonic/gin"
	"xorm.io/xorm"
)

// 公共service
var tableCommon = new(taleCommonService)

type taleCommonService struct{}

type Model map[string]interface{}

// QueryList 公共的数据库列表查询方法
func (s *taleCommonService) QueryList(tableName string, where string, args ...interface{}) (
	[]Model, error) {
	var results []Model
	session := orm.Db.Table(tableName)
	if where != "" {
		session = session.Where(where, args...)
	}
	err := session.Find(&results)
	if err != nil {
		return nil, err
	}
	return results, nil
}

// QueryListWithPage 公共的数据库列表查询方法，支持分页
func (s *taleCommonService) QueryListWithPage(c *gin.Context, tableName string, where string, page int,
	pageSize int) ([]map[string]interface{}, int64, error) {
	var results []map[string]interface{}
	accountR, _ := Request.Account(c)
	// 执行查询操作
	session := orm.Db.Table(tableName)
	session = session.Where("acid=?", accountR.Id)
	session = session.Where("deleted_at is null")
	if where != "" {
		session = session.Where(where)
	}
	// 计算偏移量
	offset := (page - 1) * pageSize
	session = session.Limit(pageSize, offset)
	count, err := session.OrderBy("id desc").FindAndCount(&results)
	if err != nil {
		return nil, 0, err
	}
	return results, count, nil
}

// QueryOne 公共的数据库单条数据查询方法
func (s *taleCommonService) QueryOne(tableName string, where string) (map[string]interface{}, error) {
	var result map[string]interface{}
	session := orm.Db.Table(tableName)
	if where != "" {
		session = session.Where(where)
	}

	has, err := session.Get(&result)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, nil
	}

	return result, nil
}

// SaveData 公共数据更新方法
func (s *taleCommonService) SaveData(tableName string, model interface{}, where, save string) (int64, error) {
	session := orm.Db.Table(tableName)
	if where != "" {
		session = session.Where(where)
	}
	var affected int64
	var err error
	if save == "update" {
		affected, err = session.Update(model)
	} else {
		affected, err = session.Insert(model)
	}
	return affected, err
}

// QueryListWithPageV2 公共的数据库列表查询方法，支持分页
func (s *taleCommonService) QueryListWithPageV2(where string, page int, pageSize int) *xorm.Session {
	session := orm.Db.Where(where)
	// 计算偏移量
	offset := (page - 1) * pageSize
	session = session.Limit(pageSize, offset).OrderBy("id desc")
	return session
}

func (s *taleCommonService) SaveVideo(c *gin.Context, url string) (string, error) {
	accountR, _ := Request.Account(c)
	jiexi, err := api345.NewConfig().Jiexi(url)
	if err != nil {
		return "", err
	}
	if jiexi.Data.Url == "" {
		return "", errors.New("解析失败【url参数缺失】")
	}
	setting, err := Upload.Setting(c)
	urlv2, err := storage.Qiniu.UploadByURLV2(jiexi.Data.Url, &storage.FormUploader{
		Suffix:  ".png",
		Acid:    accountR.Id,
		Setting: setting,
	})
	urlv2.GroupId = gconv.Int(0)
	err = Upload.Save(c, *urlv2)
	if err != nil {
		return "", err
	}
	return urlv2.Url, nil
}
